package com.android.manghe.orderpay.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.DisplayUtil
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.common.activity.PaySuccessActivity
import com.android.manghe.common.model.PaymentTypeRes
import com.android.manghe.common.webview.SimpleWebViewActivity
import com.android.manghe.config.events.PaySuccessEvent
import com.android.manghe.coupon.adapter.PaymentAdapter
import com.android.manghe.mine.activity.AddressListActivity
import com.android.manghe.mine.model.AddressInfo
import com.android.manghe.orderpay.model.AuctionOrderInfoRes
import com.android.manghe.orderpay.presenter.PAuctionOrder
import com.android.manghe.view.AutoHeightLayoutManager
import com.android.manghe.view.dialog.ConfirmPayResultDialog
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_order_pay.*

class AuctionOrderPayActivity : MVPActivity<PAuctionOrder>() {

    private val ReqCode_SelectAddress = 1000
    private var mPaymentAdapter :PaymentAdapter? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_order_pay
    }

    override fun initData(savedInstanceState: Bundle?) {
        Bus.observe<PaySuccessEvent>().subscribe {
            finish()
        }.registerInBus(this)

        p.setOrderId(intent.getStringExtra("orderId"))
        titleBar.setToolbar("结算").setLeftIcon(R.mipmap.icon_back_black).setTitleAndStatusBgColor(R.color.white)

        paymentRecyclerView.layoutManager = AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        paymentRecyclerView.addItemDecoration(RecyclerViewDivider(this, LinearLayoutManager.HORIZONTAL))
        mPaymentAdapter = PaymentAdapter(this, ArrayList<PaymentTypeRes.DataBean.PaymentBean>())
        mPaymentAdapter!!.hideDesc()
        paymentRecyclerView.adapter = mPaymentAdapter

        p.loadOrderInfo()
        p.loadAddressList()
        p.getPaymentType()

        layoutAddress.setOnClickListener {
            //添加地址,切换地址
            open(AddressListActivity::class.java, hashMapOf<String, Any>("isToSelect" to true),ReqCode_SelectAddress)
        }
        mPaymentAdapter?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as PaymentTypeRes.DataBean.PaymentBean
            mPaymentAdapter?.selectedItem(item)
            p.setPayType(item)
        }
        tvPay.setOnClickListener {
            if(p.currentAddress == null){
                ToastUtil.showShort(this@AuctionOrderPayActivity, "请填写收货地址")
            }else{
                layoutPay.visibility = View.VISIBLE
//                p.toPay(etMark.text.toString().trim())
            }
        }
        btnConfirmPay.setOnClickListener {
            //支付
            layoutPay.visibility = View.GONE
            p.toPay(etMark.text.toString().trim())
        }
        ivClosePay.setOnClickListener {
            layoutPay.visibility = View.GONE
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK){
            if(ReqCode_SelectAddress == requestCode){
                p.setCurrentAddress(data?.getSerializableExtra("addressInfo") as AddressInfo)
                showAddress(p.currentAddress)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun showGoodDetail(orderInfo: AuctionOrderInfoRes.DataBean?){
        try{
            if(orderInfo!=null) {
                GlideHelper.loadWithHolderErr(this, orderInfo.thumb, ivGoodPic)
                tvGoodTitle.text = orderInfo.title
                tvTruePrice.text = "￥${orderInfo.price}"
            }else{
                ToastUtil.showShort(this, "获取信息出错，请稍后重试")
            }
        }catch (e:Exception){
            ToastUtil.showShort(this, "获取信息出错，请稍后重试")
        }
    }

    fun showAddress(addressInfo: AddressInfo?){
        p.setCurrentAddress(addressInfo)
        if(addressInfo == null){
            layoutAddAddress.visibility = View.VISIBLE
            layoutHaveAddress.visibility = View.GONE
        }else{
            layoutAddAddress.visibility = View.GONE
            layoutHaveAddress.visibility = View.VISIBLE

            tvAddrName.text = addressInfo.name
            tvAddrTel.text = addressInfo.mobile
            tvAddr.text = addressInfo.area +" "+ addressInfo.address
        }
    }
    fun updatePayments(paymentList : List<PaymentTypeRes.DataBean.PaymentBean>){
        mPaymentAdapter?.let {
            it.update(paymentList)
        }
        try{
            val lp = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,paymentList.size * DisplayUtil.dip2px(this, 60f))
            lp.topMargin = DisplayUtil.dip2px(this, 20f)
            lp.bottomMargin = DisplayUtil.dip2px(this, 20f)
            paymentRecyclerView.layoutParams = lp
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
    }



    fun payFail(){
        ToastUtil.showShort(this, "未完成支付")
    }

    fun paySuccess(){
        finish()
        open(PaySuccessActivity::class.java)
    }
    fun toPayByH5(url: String) {
        SimpleWebViewActivity.showActivity(this, url, "支付")
    }

    fun toPayByBrowser(url: String, orderId: String) {
        val uri: Uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
        //弹出让用户确定是否支付成功的弹出框
        orderId?.let {
            val dialog = ConfirmPayResultDialog(this, orderId, object : ConfirmPayResultDialog.CallBack{
                override fun callBack(orderId: String) {
                    //显示支付成功界面
                    p.checkOrderStatus(orderId)
                }
            })
            dialog.show()
        }
    }
}